<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="queryForm" size="mini" :model="queryParams" label-position="right" label-width="auto">
        <div class="lineBox">
          <el-form-item label="操作人员" prop="actor">
            <el-input v-model="queryParams.actor" size="mini" placeholder="请输入操作人员" clearable style="width: 120px" />
          </el-form-item>
        </div>
        <div class="lineBox">
          <el-form-item label="操作对象" prop="object">
            <el-input v-model="queryParams.object" size="mini" placeholder="请输入操作对象" clearable style="width: 120px" />
          </el-form-item>
        </div>
        <div class="lineBox">
          <el-form-item label="操作类型" prop="operation_type">
            <el-select v-model="queryParams.operation_type" placeholder="请选择" clearable size="mini" style="width: 120px">
              <el-option v-for="item in operationTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </div>
        <div class="lineBox">
          <el-form-item label="操作时间" prop="dateRange">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              size="mini"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              style="width: 220px"
              @change="handleDateRangeChange"
            />
          </el-form-item>
        </div>
        <div class="lineBox">
          <el-button size="mini" type="primary" @click="handleFilter">筛选</el-button>
          <el-button size="mini" @click="resetQuery">重置</el-button>
        </div>
      </el-form>
    </div>

    <div class="myTable" style="min-height: 600px">
      <div class="filter-container">
        <div class="operation-buttons">
          <!-- 您可以在这里添加批量操作按钮 -->
        </div>
      </div>
      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        fit
        size="mini"
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column prop="sys_log_id" label="日志ID" min-width="80" align="center" />
        <el-table-column prop="actor" label="操作人员" min-width="100" align="center" show-overflow-tooltip />
        <el-table-column prop="object" label="操作内容" min-width="220" align="center" show-overflow-tooltip />
        <el-table-column label="操作类型" min-width="100" align="center">
          <template slot-scope="{row}">
            <el-tag :type="row.operation_type | operationTypeTagFilter">
              {{ row.operation_type | operationTypeFilter }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作时间" min-width="160" align="center">
          <template slot-scope="{row}">
            <span>{{ row.operation_time | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="操作备注" min-width="200" align="center" show-overflow-tooltip />
        <el-table-column fixed="right" label="操作" width="150" align="center" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button type="primary" size="mini" @click="handleViewDetails(row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        size="mini"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.limit"
        layout="total, sizes, prev, pager, next, jumper"
        @pagination="getList"
      />
    </div>

    <!-- 查看详情对话框 -->
    <el-dialog 
      title="操作日志详情" 
      :visible.sync="dialogVisible" 
      width="50%" 
      class="log-detail-dialog"
      :close-on-click-modal="false"
      :before-close="handleDialogClose"
    >
      <div class="dialog-content-wrapper">
        <div class="dialog-header">
          <div class="dialog-title">操作日志详情</div>
          <div class="log-id">日志ID: {{ currentLog.sys_log_id }}</div>
        </div>
        
        <div class="log-content">
          <div class="log-item">
            <div class="log-label">操作人员</div>
            <div class="log-value">{{ currentLog.actor }}</div>
          </div>
          
          <div class="log-item">
            <div class="log-label">操作内容</div>
            <div class="log-value long-text-content">{{ currentLog.object }}</div>
          </div>
          
          <div class="log-item">
            <div class="log-label">操作类型</div>
            <div class="log-value">
              <el-tag :type="currentLog.operation_type | operationTypeTagFilter" effect="dark">
                {{ currentLog.operation_type | operationTypeFilter }}
              </el-tag>
            </div>
          </div>
          
          <div class="log-item">
            <div class="log-label">操作时间</div>
            <div class="log-value">{{ currentLog.operation_time | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</div>
          </div>
          
          <div class="log-item">
            <div class="log-label">操作备注</div>
            <div class="log-value long-text-content">{{ currentLog.remarks }}</div>
          </div>
          
          <div class="log-item">
            <div class="log-label">用户ID</div>
            <div class="log-value">{{ currentLog.user_id }}</div>
          </div>
          
          <div class="log-item">
            <div class="log-label">创建时间</div>
            <div class="log-value">{{ currentLog.create_time | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</div>
          </div>
        </div>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleDialogClose">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { operationLogApi } from '@/api/operationlog'
import Pagination from '@/components/Pagination'
import { parseTime } from '@/utils'

export default {
  name: 'OperationLog',
  components: {
    Pagination
  },
  filters: {
    parseTime,
    operationTypeFilter(type) {
      const typeMap = {
        1: '添加',
        2: '修改',
        3: '删除',
        4:'重试',
        5:'审核'
      }
      return typeMap[type] || '未知'
    },
    operationTypeTagFilter(type) {
      const typeMap = {
        1: 'success',
        2: 'warning',
        3: 'danger',
        4: 'warning',
        5: 'success'
      }
      return typeMap[type] || 'info'
    }
  },
  data() {
    return {
      // 表格key
      tableKey: 0,
      // 列表加载状态
      listLoading: false,
      // 列表数据
      list: [],
      // 总记录数
      total: 0,
      // 查询参数
      queryParams: {
        page: 1,
        limit: 10,
        actor: undefined,
        object: undefined,
        operation_type: undefined,
        start_time: undefined,
        end_time: undefined
      },
      // 日期范围
      dateRange: [],
      // 操作类型选项
      operationTypeOptions: [
        { value: 1, label: '添加' },
        { value: 2, label: '修改' },
        { value: 3, label: '删除' },
        { value: 4, label: '重试' },
        { value: 5, label: '审核' }
      ],
      // 对话框显示状态
      dialogVisible: false,
      // 当前查看的日志
      currentLog: {}
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取操作日志列表
    async getList() {
      this.listLoading = true
      try {
        const response = await operationLogApi('getOperationLogList', this.queryParams)
        if (response.code === 200) {
          this.list = response.data.resultList || []
          this.total = response.data.totalCount || 0
        } else {
          this.$message.error(response.message || '获取操作日志列表失败')
          // 如果获取失败，使用模拟数据进行展示
          this.useTestData()
        }
      } catch (error) {
        console.error('获取操作日志列表出错:', error)
        this.$message.error('获取操作日志列表出错')
        // 如果获取失败，使用模拟数据进行展示
        this.useTestData()
      } finally {
        // 模拟请求时间
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      }
    },
    // 处理日期范围改变
    handleDateRangeChange(val) {
      if (val) {
        this.queryParams.start_time = val[0]
        this.queryParams.end_time = val[1]
      } else {
        this.queryParams.start_time = undefined
        this.queryParams.end_time = undefined
      }
    },
    // 筛选按钮点击事件
    handleFilter() {
      this.queryParams.page = 1
      this.getList()
    },
    // 重置查询条件
    resetQuery() {
      this.dateRange = []
      this.queryParams = {
        page: 1,
        limit: 10,
        actor: undefined,
        object: undefined,
        operation_type: undefined,
        start_time: undefined,
        end_time: undefined
      }
      this.getList()
    },
    // 查看日志详情
    handleViewDetails(row) {
      this.currentLog = Object.assign({}, row)
      this.dialogVisible = true
    },
    // 使用测试数据（当API不可用时）
    useTestData() {
      const now = new Date()
      const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000)
      const dayBefore = new Date(now.getTime() - 48 * 60 * 60 * 1000)
      
      this.list = [
        {
          sys_log_id: 845,
          actor: '管理员',
          object: '用户表',
          table_id: 10,
          operation_type: 1,
          operation_time: now.toISOString(),
          remarks: '添加了新用户：张三',
          user_id: 1,
          create_time: now.toISOString(),
          is_deleted: null
        },
        {
          sys_log_id: 844,
          actor: '管理员',
          object: '用户表',
          table_id: 11,
          operation_type: 2,
          operation_time: yesterday.toISOString(),
          remarks: '修改了用户信息：李四',
          user_id: 1,
          create_time: yesterday.toISOString(),
          is_deleted: null
        },
        {
          sys_log_id: 843,
          actor: '系统管理员',
          object: '角色表',
          table_id: 5,
          operation_type: 3,
          operation_time: dayBefore.toISOString(),
          remarks: '删除了角色：临时用户',
          user_id: 2,
          create_time: dayBefore.toISOString(),
          is_deleted: null
        }
      ]
      this.total = this.list.length
    },
    // 关闭弹窗
    handleDialogClose() {
      this.dialogVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.filter-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.operation-buttons {
  display: flex;
  gap: 10px;
  padding-right: 10px;
}

::v-deep .el-checkbox__label {
  font-size: 12px;
}

.custom-dialog ::v-deep .el-dialog__header {
  padding: 15px 20px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
}

.custom-dialog ::v-deep .el-dialog__title {
  font-size: 16px;
  color: #303133;
  font-weight: bold;
}

.custom-dialog ::v-deep .el-dialog__body {
  padding: 24px 24px 10px 24px;
}

.custom-dialog ::v-deep .el-dialog__footer {
  padding: 15px 24px;
  border-top: 1px solid #ebeef5;
}

.lineBox {
  display: inline-block;
  margin-right: 20px;
  margin-bottom: 10px;
}

.long-text-content {
  word-break: break-all;
  white-space: pre-wrap;
  line-height: 1.5;
  max-height: 200px;
  overflow-y: auto;
}

// 对话框样式
.log-detail-dialog {
  ::v-deep .el-dialog__header {
    padding: 0;
    display: none;
  }
  
  ::v-deep .el-dialog__body {
    padding: 0;
  }
  
  ::v-deep .el-dialog__footer {
    padding: 15px 20px;
    text-align: center;
    border-top: 1px solid #ebeef5;
    background-color: #f9fafc;
  }
  
  ::v-deep .el-dialog {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  }
}

.dialog-content-wrapper {
  background-color: #fff;
}

.dialog-header {
  background-color: #409EFF;
  color: white;
  padding: 18px 20px;
  position: relative;
  
  .dialog-title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 5px;
  }
  
  .log-id {
    font-size: 13px;
    opacity: 0.8;
  }
}

.log-content {
  padding: 20px;
}

.log-item {
  display: flex;
  margin-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 12px;
  
  &:last-child {
    margin-bottom: 0;
    border-bottom: none;
  }
  
  .log-label {
    width: 100px;
    color: #606266;
    font-weight: 500;
  }
  
  .log-value {
    flex: 1;
    color: #303133;
  }
}

.long-text-content {
  word-break: break-all;
  white-space: pre-wrap;
  line-height: 1.6;
  max-height: 200px;
  overflow-y: auto;
  background-color: #f9f9f9;
  padding: 8px 12px;
  border-radius: 4px;
  border-left: 3px solid #409EFF;
}
</style>
